<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Events\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Events\Form\EventForm;
use Events\model\Event;
use Search\Form\SearchForm;
use Zend\View\Model\JsonModel;

class PendingEventController extends AbstractActionController
{
    /* function and variables */
    protected $form;

    protected $authservice;

    protected $userinfo;

    protected $eventTable;

    protected $sessionTable;

    protected $registerTable;

    private function processData($data)
    {
        $data['ID'] = $this->generateID();
        return $data;
    }

    private function generateID()
    {
        $table_key = '1001';
        return $table_key . time();
    }

    public function getAuthService()
    {
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()->get('AuthService');
        }
        return $this->authservice;
    }

    public function getUserInfo()
    {
        if ($this->getAuthService()->getIdentity()) {
            $this->userinfo = $this->getAuthService()
                ->getStorage()
                ->read();
        }
        return $this->userinfo;
    }

    public function getSessionTable()
    {
        if (! $this->sessionTable) {
            $this->sessionTable = $this->getServiceLocator()->get('Resource\Model\SessionTable');
        }
        return $this->sessionTable;
    }

    public function getEventTable()
    {
        if (! $this->eventTable) {
            $this->eventTable = $this->getServiceLocator()->get('Event\Model\EventTable');
        }
        return $this->eventTable;
    }

    public function getRegisterTable()
    {
        if (! $this->registerTable) {
            $this->registerTable = $this->getServiceLocator()->get('Event\Model\RegisterTable');
        }
        return $this->registerTable;
    }

    protected function createEvent(array $data, $type)
    {
        $event = new Event();
        $event->exchangeArray($data);
        $this->getEventTable()->saveEvent($event, $type);
        return true;
    }
    
    /* Actions */
    public function getLatestPendingEventAction()
    {
        if ($this->getAuthService()->getIdentity()) {
            
            $latest_event = $this->getEventTable()->getLatestPendingEvent();
            $registrations = $this->getRegisterTable()->getRegistrations($latest_event->ID);
            
            return new JsonModel([
                'title' => $latest_event->TITLE,
                'place' => $latest_event->PLACE,
                'date' => $latest_event->DATE,
                'seat' => $latest_event->SEATS,
                'registrations' => $registrations
            ]);
        }
        return $this->redirect()->toRoute('Login');
    }
    
    public function getHighlightChartDataAction()
    {
        if ($this->getAuthService()->getIdentity()) {
        
            $latest_event = $this->getEventTable()->getLatestPendingEvent();
            $registrations = $this->getRegisterTable()->getRegistrations($latest_event->ID);
            $seats = $latest_event->SEATS;
            return new JsonModel([
                'available' => ($seats-$registrations)*10/$seats,
                'registered' => $registrations*10/$seats
            ]);
        }
        return $this->redirect()->toRoute('Login');
    }

    public function indexAction()
    {
        $this->layout()->setTemplate('layout/pendingeventslayout');
        
        if ($this->getAuthService()->getIdentity()) {
            
            $userinfo = $this->getUserInfo();
            $this->layout()->role = $userinfo->ROLE;
            $this->layout()->user = $userinfo->USERNAME;
            
            if (! $userinfo->ROLE == 'admin') {
                return $this->redirect()->toRoute('Login');
            }
            
            $paginator = $this->getEventTable()->fetchPendingEvents(true);
            $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
            $paginator->setItemCountPerPage(10);
            
            $searchform=new SearchForm();
            $option =$this->getEventTable()->getTableHeaders();
            $searchform->get ( 'CATEGORY' )->setAttributes ( array (
                'options' => $option
            ) );
            
            $viewmodel = new ViewModel(array(
                'paginator' => $paginator,
                'searchform'=> $searchform
            ));
            return $viewmodel;
        }
        return $this->redirect()->toRoute('Login');
    }

    public function addAction()
    {
        $this->layout()->setTemplate('layout/pendingeventslayout');
        
        if ($this->getAuthService()->getIdentity()) {
            $form = new EventForm();
            $userinfo = $this->getUserInfo();
            $this->layout()->role = $userinfo->ROLE;
            $this->layout()->user = $userinfo->USERNAME;
            
            $session_list = $this->getSessionTable()->fetchAll();
            
            $viewmodel = new ViewModel(array(
                'form' => $form,
                'id' => $this->params()->fromRoute('id'),
                'session_list' => $session_list
            ));
            
            return $viewmodel;
        } else {
            return $this->redirect()->toRoute('Login');
        }
    }

    public function editAction()
    {
        $this->layout()->setTemplate('layout/pendingeventslayout');
        
        if ($this->getAuthService()->getIdentity()) {
            $form = new EventForm();
            
            $userinfo = $this->getUserInfo();
            $this->layout()->role = $userinfo->ROLE;
            $this->layout()->user = $userinfo->USERNAME;
            
            $session_list = $this->getSessionTable()->fetchAll();
            
            $event = $this->getEventTable()->getEvent($this->params()
                ->fromRoute('id'));
            $form->bind($event);
            
            $viewModel = new ViewModel(array(
                'form' => $form,
                'id' => $this->params()->fromRoute('id'),
                'session_list' => $session_list
            ));
            $viewModel->setTemplate('events/pending-event/add');
            return $viewModel;
        } else {
            return $this->redirect()->toRoute('Login');
        }
    }

    public function processAction()
    {
        $this->layout()->setTemplate('layout/pendingeventslayout');
        
        if ($this->getAuthService()->getIdentity()) {
            
            $userinfo = $this->getUserInfo();
            $this->layout()->role = $userinfo->ROLE;
            $this->layout()->user = $userinfo->USERNAME;
            
            if (! $this->request->isPost()) {
                return $this->redirect()->toRoute(NULL, array(
                    'controller' => 'index',
                    'action' => 'add'
                ));
            }
            
            $session_list = $this->getSessionTable()->fetchAll();
            
            $post = $this->request->getPost();
            $form = new EventForm();
            $form->setData($post);
            
            if (! $form->isValid()) {
                $model = new ViewModel(array(
                    'form' => $form,
                    'id' => $this->params()->fromRoute('id'),
                    'session_list' => $session_list
                ));
                $model->setTemplate('events/pending-event/add');
                return $model;
            }
            
            $data = $form->getData();
            
            if (! isset($data['ID']) || $data['ID'] == 0) {
                $data = $this->processData($data);
                $this->createEvent($data, 0);
            } else {
                $this->createEvent($data, 1);
            }
            return $this->redirect()->toRoute('events', array(
                'controller' => 'pendingevent',
                'action' => 'index'
            ));
        } else {
            return $this->redirect()->toRoute('Login');
        }
    }

    public function searchAction()
    {
        $this->layout()->setTemplate('layout/pendingeventslayout');
        
        if ($this->getAuthService()->getIdentity()) {
           
            $userinfo = $this->getUserInfo();
            $this->layout()->role= $userinfo->ROLE;
            $this->layout()->user=$userinfo->USERNAME;
            
            if (! $userinfo->ROLE == 'admin') {
                return $this->redirect()->toRoute('Login');
            }
            $post = $this->request->getPost();
            $searchform=new SearchForm();
            $option =$this->getEventTable()->getTableHeaders();
            $searchform->get ( 'CATEGORY' )->setAttributes ( array (
                'options' => $option
            ) );
            
            $searchform->setData($post);
            
            $paginator = $this->getEventTable()->fetchAll(true);
            $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
            $paginator->setItemCountPerPage(10);
            
            if (! $searchform->isValid()) {
                $model = new ViewModel(array(
                    'paginator' => $paginator,
                    'searchform'=> $searchform            
                ));
                $model->setTemplate('events/pending-event/index');
                return $model;
            }             
            $data=$searchform->getData();
            
            $paginator = $this->getEventTable()->search(true,$data['CATEGORY'],$data['KEY'],1);
            $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
            $paginator->setItemCountPerPage(10);
            
            $viewmodel=new ViewModel(array(
                'paginator' => $paginator,
                'searchform'=> $searchform
            ));
            $viewmodel->setTemplate('events/pending-event/index');
            return $viewmodel;
        }
        return $this->redirect()->toRoute('Login');
    }
    
    public function emailAction()
    {
        $this->layout()->setTemplate('layout/additionallayout');
    
        if ($this->getAuthService()->getIdentity()) {
            return $this->redirect()->toUrl('http://www.gmail.com');
        }else {
            return $this->redirect()->toRoute('Login');
        }
    }
}